package testrank.predictors;

import testrank.SourceElementLocator;
import testrank.TestManager;

/**
 * @author Hagai Cibulski
 *
 */
final class StackTraceUtils {
	@Deprecated
	public static StackTraceElement getCallingMethod(StackTraceElement[] stackTrace) {
		// stack[0] = getStackTrace ?
		// stack[1] = .begin(
		// stack[2] = .ajc$before$
		// stack[3] = MUT execution
		// stack[4] = _aroundBody
		// stack[5] = _aroundBody ?
		// stack[6] = MUT call
		int c = 0;
		if (stackTrace[c].getMethodName().equals("getStackTrace"))
			c++;
		if (stackTrace[c].getMethodName().equals("begin"))
			c++;
		if (stackTrace[c].getMethodName().contains("ajc$before$"))
			c++;
		
		c++; // skip MUT execution
		
		if (stackTrace[c].getMethodName().contains("_aroundBody"))
			c++;
		if (stackTrace[c].getMethodName().contains("_aroundBody"))
			c++;

		return stackTrace[c]; // MUT call
	}
	
	@Deprecated
	public static String toCanonicalSignature(StackTraceElement element) {
		String fileName = element.getFileName();
		int lineNumber = element.getLineNumber();
		return toCanonicalSignature(fileName, lineNumber);
	}

	public static String toCanonicalSignature(String elementSignature) {
		String elementSignature1 = elementSignature.split("\\(")[1];
		String elementSignature2 = elementSignature1.split("\\)")[0];
		String[] location = elementSignature2.split(":");
		if (location.length != 2) {
			System.out.println(elementSignature2);
		}
		assert(location.length == 2);
		String fileName = location[0];
		String lineString = location[1];
		int lineNumber = Integer.parseInt(lineString);
		String method = toCanonicalSignature(fileName, lineNumber);
		return method;
	}

	public static String toCanonicalSignature(String fileName, int lineNumber) {
		String method = toCanonicalSignature(TestManager.testLocator(), fileName, lineNumber);
		if (method == null) {
			method = toCanonicalSignature(TestManager.locator(), fileName, lineNumber);
		}
		return method;
	}
	
	private static String toCanonicalSignature(SourceElementLocator locator, String fileName, int lineNumber) {
		String method = locator.locateMethod(fileName, lineNumber);
		return method;
	}
}
